<template>
  <div class="container">
    <el-card shadow="never">
      <!-- 试题录入 标题 -->
      <div slot="header" class="clearfix">
        <span>{{ this.id ? "试题修改" : "试题录入" }}</span>
      </div>

      <!-- 表单区域 -->
      <el-form
        :model="formData"
        ref="formRef"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="学科" prop="subjectID">
          <el-select
            v-model="formData.subjectID"
            placeholder="请选择"
            @change="getDirectorysList($event)"
          >
            <el-option
              v-for="item in form.subjectList"
              :key="item.id"
              :value="item.id"
              :label="item.subjectName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目录" prop="catalogID">
          <el-select
            v-model="formData.catalogID"
            placeholder="请选择"
            @change="getCatalog($event)"
          >
            <el-option
              v-for="item in form.directoryList"
              :key="item.id"
              :value="item.id"
              :label="item.directoryName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业" prop="enterpriseID">
          <el-select
            v-model="formData.enterpriseID"
            placeholder="请选择"
            @change="getEnterprise($event)"
          >
            <el-option
              v-for="item in form.companyList"
              :key="item.id"
              :value="item.id"
              :label="item.company"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="城市" prop="city">
          <div class="city">
            <el-select
              v-model="formData.province"
              placeholder="请选择"
              @change="getCitysList($event)"
            >
              <el-option
                v-for="item in form.provincesList"
                :key="item.id"
                :value="item"
              ></el-option>
            </el-select>
            <el-select v-model="formData.city" placeholder="请选择">
              <el-option
                v-for="item in form.citysList"
                :key="item.id"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>

        <el-form-item label="方向" prop="direction">
          <el-select
            v-model="formData.direction"
            placeholder="请选择"
            filterable
            allow-create
            default-first-option
          >
            <el-option
              v-for="item in form.directionList"
              :key="item.id"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题型" prop="questionType">
          <el-radio-group v-model="formData.questionType">
            <el-radio
              v-for="item in form.questionTypeList"
              :key="item.value"
              :value="item.value"
              :label="item.value + ''"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="formData.difficulty">
            <el-radio
              v-for="item in form.difficultyList"
              :key="item.value"
              :label="item.value + ''"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="题干" prop="question">
          <quill-editor
            v-model="formData.question"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="contentRules"
          >
          </quill-editor>
        </el-form-item>

        <el-form-item
          label="选项 :"
          class="option-from width500 choise"
          size="small"
          v-if="formData.questionType === '1'"
          prop="options"
        >
          <!-- 单选 -->
          <span
            class="option"
            v-for="(item, index) in optionTypeList"
            :key="index"
          >
            <el-radio-group v-model="singleChoice">
              <el-radio v-model="item.isRight" :label="item.code"
                >{{ item.code }}：</el-radio
              >
            </el-radio-group>
            <el-input v-model="item.title" class="option-input"></el-input>
            <div class="upload-img">
              <el-upload
                action="https://jsonplaceholder.typicode.com/posts/"
                list-type="picture-card"
                :on-remove="
                  (file) => {
                    handleRemove(file, index);
                  }
                "
                class="display-img"
                :name="item.img"
                :on-change="
                  (file) => {
                    onChange(file, index);
                  }
                "
              >
                上传图片
              </el-upload>
              <div class="delete-img">x</div>
            </div>
          </span>
          <el-button
            type="danger"
            class="add-options-answer"
            @click="addQuestion"
            disabled
            >+增加选项与答案</el-button
          >
        </el-form-item>
        <!-- 多选 -->
        <el-form-item
          label="选项 :"
          class="option-from width500 choise"
          size="small"
          v-if="formData.questionType === '2'"
          prop="options"
        >
          <span
            class="option"
            v-for="(item, index) in optionTypeLists"
            :key="index"
          >
            <el-checkbox-group v-model="multipleChoice">
              <el-checkbox v-model="item.isRight" :label="item.code"
                >{{ item.code }}：</el-checkbox
              >
            </el-checkbox-group>
            <el-input v-model="item.title" class="option-input"></el-input>
            <div class="upload-img">
              <el-upload
                action="https://jsonplaceholder.typicode.com/posts/"
                list-type="picture-card"
                :on-remove="
                  (file) => {
                    handleRemove(file, index);
                  }
                "
                class="display-img"
                :name="item.img"
                :on-change="
                  (file) => {
                    onChange(file, index);
                  }
                "
              >
                上传图片
              </el-upload>
              <div class="delete-img">x</div>
            </div>
          </span>
          <el-button
            type="danger"
            class="add-options-answer"
            @click="addQuestion"
            >+增加选项与答案</el-button
          >
        </el-form-item>

        <el-form-item label="解析视频" prop="videoURL">
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :before-remove="beforeRemove"
            multiple
            :file-list="formData.fileList"
            :show-file-list="false"
          >
            <el-input
              v-model="formData.videoURL"
              placeholder="请上传视频"
            ></el-input>
          </el-upload>
        </el-form-item>

        <el-form-item label="答案解析" prop="answer">
          <quill-editor
            v-model="formData.answer"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="contentRules"
          >
          </quill-editor>
        </el-form-item>

        <el-form-item label="题目备注" prop="remarks">
          <el-input type="textarea" v-model="formData.remarks"></el-input>
        </el-form-item>

        <el-form-item label="试题标签" prop="tags">
          <el-select
            filterable
            allow-create
            default-first-option
            v-model="formData.tags"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in form.tagsList"
              :key="item.id"
              :value="item.tagName"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button v-if="!this.exist" type="primary" @click="submitForm"
            >确定提交</el-button
          >
          <el-button v-else type="success" @click="editForm"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 获取学科列表
import { list as getSubjects } from '@/api/hmmm/subjects.js'
// 获取目录列表
import { list as getDirectorys } from '@/api/hmmm/directorys.js'
// 获取企业列表
import { list as getCompanys } from '@/api/hmmm/companys.js'
// 获取城市列表
import { provinces as getProvinces, citys as getCitys } from '@/api/hmmm/citys.js'
// 获取标签列表
import { list as getTags } from '@/api/hmmm/tags.js'
// 获取方向
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// 获取基础题库
import {
  detail as getQuestions,
  update as editQuestions,
  add as addQuestions
} from '@/api/hmmm/questions.js'

export default {
  name: 'questionsNew',
  components: {
    quillEditor
  },
  props: {
    value: {
      type: [String, Number, Object]
    }

  },
  data () {
    return {
      id: '',
      form: {
        subjectList: {},
        directoryList: [],
        companyList: {},
        provincesList: [],
        citysList: [],
        tagsList: [],
        directionList: direction,
        questionTypeList: questionType,
        difficultyList: difficulty
      },
      formData: {
        subject: '',
        subjectID: '',
        catalog: '',
        catalogID: '',
        enterprise: '',
        enterpriseID: '',
        province: '',
        city: '',
        tags: [],
        direction: '',
        questionType: '',
        difficulty: '',
        question: '',
        answer: '',
        videoURL: '',
        remarks: '',
        fileList: [],
        options: []
      },
      editorOption: {
        // some quill options
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请填写题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请填写答案解析', trigger: 'blur' }
        ],
        options: [],
        remarks: [],
        tags: [],
        video: [],
        choise: [],
        videoURL: [],
        questionType: [],
        difficulty: []
      },
      //  单选选中项
      singleChoice: '',
      //  多选选中项
      multipleChoice: [],
      // 选项
      /* code: '', // 代码
          title: '', //  标题
          img: '', // 图片URL
          isRight: ''// 是否正确答案
       */

      // 单选
      optionTypeList: [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: null
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: null
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: null
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: null
        }
      ],
      // 多选
      optionTypeLists: [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: null
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: null
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: null
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: null
        }
      ]
    }
  },
  mounted () {

  },
  created () {
    this.initForm()
  },
  /*  watch: {
    formData (newval, old) {
      console.log(newval, old)
      if (newval.subject) {
        this.initForm()
        this.getDirectorysList(newval.subjectID)
      }
    }
  }, */
  methods: {

    initForm () {
      this.id = this.$route.params.id
      console.log(this.id)
      if (this.exist) {
        this.getQuestionsList()
      }
      this.getSubjectsList()
      this.getCompanysList()
      this.getProvincesList()
    },
    // 获取题库列表
    async getQuestionsList () {
      const { data } = await getQuestions({ id: this.id })
      data.tags = data.tags.split(',')
      this.formData = data
      console.log(this.formData)
      console.log(this.formData.tags)
      if (data.options.length > 0) {
        // 判断选项是否是单选
        // 单选
        if (data.questionType === '1') {
          this.optionTypeList = data.options
          data.options.forEach((val) => {
            if (val.isRight === 1) {
              this.singleChoice = val.code
            }
          })
        } else if (data.questionType === '2') { // 多选
          this.optionTypeLists = data.options
          data.options.forEach((item) => {
            if (item.isRight === 1) {
              this.multipleChoice.push(item.code)
            }
          })
        }
      }
    },
    // 获取学科列表
    async getSubjectsList () {
      const { data } = await getSubjects({ pagesize: 20 })
      // console.log(data.items)
      this.form.subjectList = data.items
      if (this.exist) { this.getDirectorysList(this.formData.subjectID) }
    },
    // 获取 学科名字 以及目录列表
    async getDirectorysList (e) {
      if (!this.exist) {
        // console.log(e)
        let item = {}
        item = this.form.subjectList.find((item) => {
          return item.id === e//
        })
        this.formData.subject = item.subjectName
        this.formData.catalogID = ''
      }
      // 获取目录
      const { data } = await getDirectorys({ subjectID: e, pagesize: 20 })
      // console.log(data)
      this.form.directoryList = data.items

      if (this.exist) {
        this.getTagsList(this.formData.subjectID)
      } else {
        this.getTagsList(e)
      }
    },
    // 获取目录名字
    getCatalog (e) {
      let item = {}
      item = this.form.directoryList.find((item) => {
        return item.id === e//
      })
      // console.log(item)
      this.formData.catalog = item.directoryName
      // console.log(this.formData.catalog)
    },
    // 获取企业列表
    async getCompanysList () {
      const { data } = await getCompanys({ pagesize: 20 })
      // console.log(data)
      this.form.companyList = data.items
    },
    // 获取企业名字
    getEnterprise (e) {
      let item = {}
      item = this.form.companyList.find((item) => {
        return item.id === e//
      })
      // console.log(item)
      this.formData.enterprise = item.company
      // console.log(this.formData.enterprise)
    },
    // 获取城市列表
    getProvincesList () {
      const data = getProvinces()
      //   console.log(data)
      this.form.provincesList = data
    },
    // 获取城区列表
    getCitysList (e) {
      this.formData.city = ''
      const data = getCitys(e)
      // console.log(data)
      this.form.citysList = data
    },
    // 获取标签列表
    async getTagsList (e) {
      const { data } = await getTags({ subjectID: e, pagesize: 20 })
      console.log(data.items)
      this.form.tagsList = data.items
    },
    onEditorBlur (quill) {
      console.log('editor blur!', quill)
    },

    handlePreview (file) {
      console.log(file)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleChange (file) {
      this.formData.videoURL = URL.createObjectURL(file.raw)
    },
    contentRules () {
      this.$refs.formRef.validate(this.rules)
    },
    // 点击增加选项
    addQuestion () {
      const letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
      //  多选
      if (this.formData.questionType === '2') {
        if (this.optionTypeLists.length >= letter.length) {
          this.$message({
            message: '已经为最多选项了，不能再添加了',
            type: 'warning',
            offset: 100
          })
        } else {
          this.optionTypeLists.push({
            code: letter[this.optionTypeLists.length],
            title: '',
            img: '',
            isRight: null
          })
        }
      }
    },
    // 图片操作
    // 删除图片
    handleRemove (file, index) {
      console.log('删除图片操作')
      console.log(file, index)
    },
    /* handlePictureCardPreview (file) {
      console.log(222)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }, */
    // 获取图片
    onChange (file, index) {
      console.log(file, index)
      this.optionTypeList[index].img = file.url
    },
    // 单选多选操作
    selectAction () {
      // 单选
      if (this.formData.questionType === '1') {
        this.formData.options = []
        // 让选中的内容的isRight为true
        this.optionTypeList.forEach((val, i) => {
          this.formData.options.push({
            code: val.code,
            title: val.title,
            img: val.img,
            isRight: val.code === this.singleChoice ? 1 : 0
          })
        })
      } else if (this.formData.questionType === '2') { // 多选
        // 让选中的内容的isRight为true
        this.formData.options = this.optionTypeLists
        this.formData.options.forEach((val, i) => {
          var f = this.multipleChoice.find(t => t === val.code)
          this.formData.options[i].isRight = f ? 1 : 0
        })
      }
    },

    // 提交表单
    async submitForm () {
      this.selectAction()
      this.$refs.formRef.validate(this.rules)
      console.log(this.$refs.formRef.model)

      try {
        await addQuestions(this.addFormData)
        this.$message({
          message: '恭喜你，提交成功',
          type: 'success'
        })
        this.$refs.formRef.resetFields()
        this.$router.push('/questions/list')
      } catch (error) {
        console.log(error)
        // this.$message.error('很抱歉，提交失败')
      }
    },
    async editForm () {
      this.$refs.formRef.validate(this.rules)
      this.selectAction()
      console.log(this.$refs.formRef.model)
      try {
        await editQuestions(this.addFormData)
        this.$message({
          message: '恭喜你，修改成功',
          type: 'success'
        })
        this.$refs.formRef.resetFields()
      } catch (error) {
        console.log(error)
        // this.$message.error('很抱歉，提交失败')
      }
    }

  },
  computed: {
    addFormData: function () {
      const addForm = this.$refs.formRef.model
      addForm.questionType = addForm.questionType.toString()
      addForm.difficulty = addForm.difficulty.toString()
      addForm.tags = addForm.tags.toString()
      return addForm
    },
    exist: function () {
      var e = this.id !== '' && this.id !== ':id'
      return e
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.city .el-input__inner {
  width: 200px !important;
}
/deep/ .choise .el-input__inner {
  width: 250px !important;
}
/deep/ .el-input__inner,
/deep/.el-textarea__inner,
/deep/ .el-upload-list--text {
  width: 400px !important;
}

.quill-editor {
  margin-bottom: 22px;
  /deep/.ql-editor {
    height: 300px;
  }
}

// 选项
.option-from {
  margin: 10px 0;
  padding: 20px 0;
  .option {
    display: flex;
    position: relative;
    margin-bottom: 55px;
    .option-input {
      box-sizing: border-box;
      /deep/.el-input__inner {
        width: 300px;
      }
    }
    .el-radio-group {
      line-height: inherit;
    }
    /deep/.el-upload-list {
      display: block;
      position: absolute;
      top: -10px;
      left: 135px;
      width: 100px;
      height: 100px;
      .el-upload-list__item {
        height: 100px;
        width: 100%;
        .el-upload-list__item-thumbnail {
          height: 100%;
        }
      }
    }
    .el-radio {
      line-height: unset;
      margin-right: 0;
    }
    .el-input {
      width: 300px;
      margin-right: 5px;
    }

    .upload-img {
      height: 50px;
      width: 100px;
      position: absolute;
      top: -22px;
      left: 320px;
      /deep/.el-upload--picture-card {
        height: 75px;
        width: 125px;
        line-height: 75px;
        background-color: #fff;
      }
      .delete-img {
        position: absolute;
        top: -8px;
        left: 116px;
        width: 16px;
        height: 16px;
        border: 1px solid #ccc;
        border-radius: 50%;
        line-height: 14px;
        text-align: center;
        font-size: 7px;
        color: #ccc;
        background-color: #fff;
        cursor: pointer;
      }
    }
  }
  .add-options-answer {
    padding: 10px 20px;
  }
}
</style>
